package api

import (
	"fmt"
	"mytest/initialize/database"
	"mytest/models"
	"mytest/models/request"
	"mytest/service/system"
	"net/http"

	"github.com/gin-gonic/gin"
)

func UpdateCasbin(c *gin.Context) {
	var cas request.CasbinInReceive
	if e := c.Bind(&cas); e != nil {
		c.String(http.StatusBadRequest, "bad request: %v", e.Error())

		return
	}
	if cas.AuthorityId == "" || len(cas.CasbinInfos) == 0 {
		c.String(http.StatusOK, "参数错误")
		return
	}
	success, err := system.UpdateCasbin(cas)
	if err != nil {
		c.String(http.StatusOK, "错误:%v", err)
	}

	c.String(http.StatusOK, "%v", success)
}
func GetCasbinById(c *gin.Context) {
	var form request.GetById
	if e := c.Bind(&form); e != nil {
		c.String(http.StatusBadRequest, "bad request: %v", e.Error())

		return
	}
	if form.Auth == "" {
		c.String(http.StatusOK, "输入角色id")
		return
	}
	out := system.GetCasbinById(form.Auth)

	c.JSON(http.StatusOK, UniversalResp{
		Data: out,
		Msg:  "success",
	})
}
func AllApis(c *gin.Context) {
	var req request.MenuList
	if e := c.Bind(&req); e != nil {
		c.String(http.StatusBadRequest, "bad request: %v", e.Error())

		return
	}
	db := database.GetDB()
	e, apis, total := system.GetApiList(db, req)
	if e != nil {
		c.JSON(http.StatusOK, UniversalResp{
			Code: 1,
			Msg:  fmt.Sprintf("api获取失败: %v", e.Error()),
		})
		return
	}

	c.JSON(http.StatusOK, UniversalResp{
		Data: gin.H{
			"total": total,
			"data":  apis,
		},
	})
}
func CreateApi(c *gin.Context) {
	var form models.SysApis
	if e := c.Bind(&form); e != nil {
		c.String(http.StatusBadRequest, "bad request: %v", e.Error())

		return
	}
	if form.Name == "" || form.Path == "" || form.Method == "" {
		c.JSON(http.StatusOK, UniversalResp{
			Code: 1,
			Msg:  "参数不全",
		})
		return
	}
	db := database.GetDB()
	e := system.CreateApi(db, &form)
	if e != nil {
		c.JSON(http.StatusOK, UniversalResp{
			Code: 1,
			Msg:  fmt.Sprintf("api增加失败: %v", e.Error()),
		})
		return
	}

	c.JSON(http.StatusOK, UniversalResp{
		Msg: "success",
	})
}
